import { getSuccessBill, getReturnList, getOrderList, getOrderIng, getRefuseOrder ,cancelOrder} from "../../../network/order";
import { debounce,callTel, toast,Filter } from '../../../utils/Tools'
import moment from '../../../utils/moment';

Page({
  data: {
    active:0,
    search:null,
    timeArr:[],
    dateArr:[],
    date:0,
    isBill: false,
    orderList:[],
    returnOrder:[],
    orderIngList:[],
    billList:[],
    returnList:[],
    status:{
      '0':'审核中','1':'进行中'
    },
    afterlist:[],
    needScroll: true,
    origial:[],
    dates:-1,
  },
  onLoad: function (options) {
    this.handleFilter = debounce(this.handleFilter,100)
  },
  async handleFilter(e){
      const res = await Filter(e.detail,this.data.origial)
      this.setData({
        orderList:res,
        returnOrder:res,
        billList:res,
        afterlist:res,
      })
  },
  //      事件函数      //
  forbidScroll(e) {
    return;
  },
  async onShow(){
    //   调用网络请求
    if(this.data.active === 0){
      this._getSuccessBill()
    }else if(this.data.active === 1){
      const orderIng = await getOrderIng()
      if(orderIng.code === 200){
        this.setData({
          orderIngList: orderIng.data,
          afterlist:this.data.orderIngList
        })
      }
      this.handleDate(this.data.orderIngList)
    }else if(this.data.active === 2){
      const orderIng = await getOrderIng()
      if(orderIng.code === 200){
        this.setData({
          orderIngList: orderIng.data,
          afterlist:orderIng.data
        })
      }
      this.handleDate(this.data.orderIngList)

    }else if(this.data.active === 3){
      const billRes = await getSuccessBill()
      if(billRes.code === 200){
        this.setData({
          billList:billRes.data,
          afterlist:billRes.data
        })
      }
      this.handleDate(this.data.billList)
    }
  },
  //撤销按钮
  drawOrder(e){
    let uid=e.currentTarget.dataset.id;
    let index=e.currentTarget.dataset.index;
    wx.showModal({
      title: '撤销订单',
      content:'确认撤销该订单吗',
      success:(res)=>{
        if(res.confirm===true){
          wx.request({
            url: 'https://master.gddzxcx.com/api/'+'orders/cancel_order',
            method:'Post',
            data:{
              order_id:uid,
              token:wx.getStorageSync("token")
            },
            success:res=>{
              if(res.code===500){
                wx.showToast({
                  title: '操作失败',
                  icon: 'none',
                  duration: 1500,
                  mask: true
                  });
              }else{
                this.data.orderList.splice(index,1)
                this.setData({
                  orderList:this.data.orderList
                })
                wx.showToast({
                  title: '撤销成功',
                  icon:'none',
                  duration:1000,
                  mask:true,
                })
              }
              console.log(res)
            },
            fail:err=>{
              console.log(err)
            }
          })
        }
      }
    })
  },
  handleGoto(e){
    const {id,code} = e.currentTarget.dataset
    console.log(id,code)
    wx.navigateTo({
      url: `/pages/order/order-detail/order-detail?order_id=${id}&code=${code}`
    });
  },
  saveImage (e) {
    let _this = this
    wx.showActionSheet({
        itemList: ['保存到相册'],
        success(res) {
            let url = e.currentTarget.dataset.url;
            wx.getSetting({
                success: (res) => {
                    if (!res.authSetting['scope.writePhotosAlbum']) {
                        wx.authorize({
                            scope: 'scope.writePhotosAlbum',
                            success: () => {
                                // 同意授权
                                _this.saveImgInner(url);
                            },
                            fail: (res) => {
                                wx.showModal({
                                    title: '保存失败',
                                    content: '请开启访问手机相册权限',
                                    success(res) {
                                        wx.openSetting()
                                    }
                                })
                            }
                        })
                    } else {
                      // 已经授权了
                      _this.saveImgInner(url);
                    }
                },
                fail: (res) => {
                  toast('取消保存')
                }
            })   
        },
        fail(res) {
          toast('取消保存')
        }
    })
},
// 长按保存功能--保存部分
saveImgInner (url) {
    wx.getImageInfo({
        src: url,
        success: (res) => {
            let path = res.path;
            wx.saveImageToPhotosAlbum({
                filePath: path,
                success: (res) => {
                    console.log(res);
                    wx.showToast({
                        title: '已保存到相册',
                    })
                },
                fail: (res) => {
                    console.log(res);
                }
            })
        },
        fail: (res) => {
            console.log(res);
        }
    })
},
  handleDate(arr){
    console.log('54644645645')
    let date = [];
    let timeArr = [];
    if(arr){

      arr.forEach(res=>{
        const time = res.create_time*1000
        date.push(moment(time,'YYYY.MM'))
        timeArr.push(moment(time,'YYYY.MM'))
      })
    }
    if(date.length>0){
      this.data.dateArr=[];
      this.data.dateArr=[{text:'不限',value:-1}]
      Array.from(new Set(date)).forEach((res,index)=>{
        this.setData({
          dateArr:this.data.dateArr.concat({text:res,value:index}),
          origial:arr,
          dates:-1,
          // dataArr:this.data.dateArr
        })
      })
    }
    if(timeArr.length>0){
      this.data.timeArr=[]
      Array.from(new Set(timeArr)).forEach((res,index)=>{
        this.setData({
          timeArr:this.data.timeArr.concat(res),
          origial:arr,
          dates:-1,
        })
      })
    }
  },
  async handleTabActive(e){ // 处理导航切换
    const {index} = e.detail
    this.setData({dateArr:[],date:0,search:null,timeArr:[],active:index})
    if(index === 0){
      this._getSuccessBill()
      return;
    }
    if(index === 1){
      const ReturnRes = await getRefuseOrder()
      if(ReturnRes.code === 200){
        this.setData({
          returnOrder:ReturnRes.data,
          afterlist:ReturnRes.data
        })
      }
      this.handleDate(this.data.returnOrder)
      return;
    }
    if(index === 2){
      const orderIng = await getOrderIng()
      if(orderIng.code === 200){
        this.setData({
          orderIngList: orderIng.data,
          afterlist:orderIng.data
        })
      }
      this.handleDate(this.data.orderIngList)
      return;
    }
    if(index === 3){
      const billRes = await getSuccessBill()
      if(billRes.code === 200){
        this.setData({
          billList:billRes.data,
          afterlist:billRes.data
        })
      }
      this.handleDate(this.data.billList)
      // console.log(this.data.billList,'11111111111111111111111111111')
    }else{
      const returnRes = await getReturnList()
      if(returnRes.code === 200){
        this.setData({
          returnList: returnRes.data
        })
      }
    }
  },
  handleCallTel(e){
    const {phone} = e.currentTarget.dataset
    callTel(phone)
  },
  // handleFilter(e){  //处理搜索
  //   const {type} = e.currentTarget.dataset
  //   const result = this.data[type].filter(res =>{
  //     if(res.standards === null) return
  //     return res.standards.includes(e.detail)
  //   })
  //   if(!result) this.setData({afterlist:this.data[type]})
  //   this.setData({afterlist:result})
  // },
  // handleFinishFilter(e){  // 处理已完成搜索
  //   const result = this.data.billList.filter(res =>{
  //     if(res.servicer_name === null) return
  //     return res.servicer_name.includes(e.detail)
  //   })
  //   if(!result) this.setData({afterlist:this.data.billList})
  //   this.setData({afterlist:result})
  // },
  handleSalesMenu(e){  //  处理下拉菜单选择
    console.log(e)
    this.setData({
      date: e.detail,
      needScroll:false
    })
    if(e.detail!==-1){
      console.log('333333333')
    const result = this.data.origial.filter(res=>{
    const time = moment(res.create_time*1000,'YYYY.MM')
      return time.includes(this.data.timeArr[this.data.date])
    })
  
    if(!result) this.setData({afterlist:this.data.orderList})
    console.log(result)
 
    this.setData({
      orderList:result,
      returnOrder:result,
      billList:result,
      afterlist:result,
      // afterlist:result
    })
  }else{
    this.setData({
      orderList:this.data.origial,
      returnOrder:this.data.origial,
      billList:this.data.origial,
      afterlist:this.data.origial,
    })
  }
  },
  handleBill(){  // 处理遮罩层显示
    this.setData({isBill:true})
  },
  onClickHide() {  //   处理遮罩层隐藏
    this.setData({ isBill: false });
  },
  handleStatus(e){
    const {index} = e.currentTarget.dataset
    wx.showModal({
      title: '操作确认',
      content: '是否重新提交该订单',
      success: (result) => {
        if(result.confirm){
          
        }
      }
    });
  },
  //      网络请求      //
  async _getSuccessBill(){
    const orderRes = await getOrderList()
    if(orderRes.code === 200){
      this.setData({
        orderList: orderRes.data,
        afterlist:orderRes.data,
        dates:-1,
      })
    }
    this.handleDate(orderRes.data)
    // console.log(orderRes.data)
  }
})